import React, { useState, useEffect } from 'react'
import styles from './index.module.scss'
import classNames from 'classnames'

function HouseMatch ({ data, onChange, readonly }) {
  const [HOUSE_PACKAGE] = useState([
    {
      id: 1,
      name: '衣柜',
      icon: 'icon-wardrobe'
    },
    {
      id: 2,
      name: '洗衣机',
      icon: 'icon-wash'
    },
    {
      id: 3,
      name: '空调',
      icon: 'icon-air'
    },
    {
      id: 4,
      name: '天然气',
      icon: 'icon-gas'
    },
    {
      id: 5,
      name: '冰箱',
      icon: 'icon-ref'
    },
    {
      id: 6,
      name: '暖气',
      icon: 'icon-Heat'
    },
    {
      id: 7,
      name: '电视',
      icon: 'icon-vid'
    },
    {
      id: 8,
      name: '热水器',
      icon: 'icon-heater'
    },
    {
      id: 9,
      name: '宽带',
      icon: 'icon-broadband'
    },
    {
      id: 10,
      name: '沙发',
      icon: 'icon-sofa'
    }
  ])

  const [housePackage, setHousePackage] = useState(null)
  const [selectedList, setSelectedList] = useState([])

  const toggleSelect = name => {
    if (readonly) return

    let oldList = [...selectedList]
    if (oldList.includes(name)) {
      oldList = oldList.filter(item => item !== name)
    } else {
      oldList.push(name)
    }

    setSelectedList(oldList)
  }

  useEffect(() => {
    onChange && onChange(selectedList.join('|'))
  }, [selectedList])

  useEffect(() => {
    if (data) {
      setHousePackage(HOUSE_PACKAGE.filter(item => data.includes(item.name)))
    } else {
      setHousePackage(HOUSE_PACKAGE)
    }
  }, [])

  return (
    <ul className={styles.root}>
      {housePackage &&
        housePackage.map(item => {
          return (
            <li
              className={classNames(styles.item, {
                [styles.active]: selectedList.includes(item.name)
              })}
              key={item.id}
              onClick={() => toggleSelect(item.name)}
            >
              <p>
                <i
                  className={classNames(`iconfont ${item.icon}`, styles.icon)}
                />
              </p>
              {item.name}
            </li>
          )
        })}
    </ul>
  )
}

HouseMatch.defaultProps = {
  readonly: true
}

export default HouseMatch
